package com.cdp.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.*;
import com.cdp.system.dto.RegionDTO;
import com.cdp.system.mapper.SysEfficiencyAgentMapper;
import com.cdp.system.mapper.SysSwellingagentMapper;
import com.cdp.system.mapper.SysWaterReducerMapper;
import com.cdp.system.service.IRegionService;
import com.cdp.system.service.IsysRegionService;
import com.cdp.system.vo.RegionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import com.cdp.system.service.*;


/**
 * 地区信息
 */
@RestController
@RequestMapping("/system/region")
public class SysRegionController {


    @Autowired
    private IsysRegionService isysRegionService;

    @Autowired
    private IRegionService regionService;

    @Autowired
    private ISysFlyashService sysFlyashService;

    @Autowired
    private ISysSandFinenesService sysSandFinenesService;

    @Autowired
    private ISysSandTypeService sysSandTypeService;

    @Autowired
    private ISysSandService sysSandService;

    @Autowired
    private ISysStoneGrainService sysStoneGrainService;

    @Autowired
    private ISysFlyashTypeService sysFlyashTypeService;

    @Autowired
    private ISysFlyashFinenessService sysFlyashFinenessService;

    @Autowired
    private ISysWaterReducerTypeService sysWaterReducerTypeService;

    @Autowired
    private ISysCementService sysCementService;

    @Autowired
    private ISysStoneService sysStoneService;

    @Autowired
    private ISysWaterReducerService sysWaterReducerService;

    @Autowired
    private SysWaterReducerMapper sysWaterReducerMapper;

    @Autowired
    private ISysStoneSizeService stoneSizeService;

    @Autowired
    private ISysSourceNameService sysSourceNameService;
    @Autowired
    private ISysEfficiencyMerchantNameService sysEfficiencyMerchantNameService;


    @Autowired
    private ISysMechanicalPerformanceService sysMechanicalPerformanceService;

    @Autowired
    private ISysSlumpService sysSlumpService;

    @Autowired
    private ISysDeformationPerformanceService sysDeformationPerformanceService;

    @Autowired
    private ISysEfficiencyAgentService sysEfficiencyAgent;

    @Autowired
    private ISysDurabilityPerformanceService sysDurabilityPerformanceService;

    @Autowired
    private ISysWaterService waterService;

    @Autowired
    private ISysMineralPowderService sysMineralPowderService;

    @Autowired
    private SysOtherAdmixturesService sysOtherAdmixturesService;


    @Autowired
    private ISysWaterModelService sysWaterModelService;

    @Autowired
    private ISysSwellingagentService sysSwellingagentService;

    @Autowired
    private ISysCementModelService sysCementModelService;


    @Autowired
    private ISysCementStabilityService sysCementStabilityService;

    @Autowired
    private ISysStoneModelService sysStoneModelService;

    @Autowired
    private ISysStoneSpecificationService sysStoneSpecificationService;


    @Autowired
    private ISysStoneParticlesizedistributionService sysStoneParticlesizedistributionService;


    @Autowired
    private ISysMineralModelService sysMineralModelService;

    @Autowired
    private ISysOtherAdmixturesModelService sysOtherAdmixturesModelService;


    @GetMapping("listRegions")
    public AjaxResult listRegions() {

        List<SysRegion> regionList = isysRegionService.listRegions();
        return AjaxResult.success(regionList);
    }


    /**
     * 地区模糊查询
     */

    // @PostMapping("/listMistedRegions")
    public AjaxResult listMistedRegions(@RequestBody RegionDTO regionDTO) {
        String regionName = regionDTO.getRegionName();
        List<SysRegion> regionList = isysRegionService.listMistedRegions(regionName);
        return AjaxResult.success(regionList);
    }


    /**
     * 查询地区集合
     *
     * @return
     */
    //@GetMapping("query/region")
    @PostMapping("/listMistedRegions")
    public AjaxResult queryRegion(@RequestBody RegionDTO regionDTO) {
        String regionName = regionDTO.getRegionName();
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();

        if (regionName != null && !regionName.trim().isEmpty()) {
            queryWrapper.like("full_name", regionName);
        }

        List<Region> list = regionService.list(queryWrapper);
        List<RegionVO> arrayList = new ArrayList<>();

        for (Region region : list) {
            RegionVO regionVO = new RegionVO();


            BeanUtils.copyProperties(region, regionVO);
            regionVO.setValue(region.getId());
            regionVO.setRegionName(region.getFullName());
            arrayList.add(regionVO);
        }

        return AjaxResult.success(arrayList);
    }


    /**
     * 查询水泥所在的地区
     *
     * @return
     */
    @GetMapping("queryCementRegions")
    public AjaxResult queryCementRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysCement> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysCement::getRegionName);
        List<SysCement> cementList = sysCementService.list(cementWrapper);

        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysCement::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 查询石头表所在地区
     *
     * @return
     */

    @GetMapping("queryStoneRegions")
    public AjaxResult queryStoneRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysStone> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysStone::getRegionName);
        List<SysStone> cementList = sysStoneService.list(cementWrapper);

        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysStone::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 查询砂表所在地区
     *
     * @return
     */

    @GetMapping("querySandRegions")
    public AjaxResult querySandRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysSand> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysSand::getRegionName);
        List<SysSand> cementList = sysSandService.list(cementWrapper);

        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysSand::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 查询粉煤灰表所在地区
     *
     * @return
     */

    @GetMapping("querySysFlyashRegions")
    public AjaxResult querySysFlyashRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysFlyash> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysFlyash::getRegionName);
        List<SysFlyash> cementList = sysFlyashService.list(cementWrapper);


        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysFlyash::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 查询矿粉表所在地区
     *
     * @return
     */

    @GetMapping("queryMineralPowderRegions")
    public AjaxResult queryMineralPowderRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysMineralPowder> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysMineralPowder::getRegionName);
        List<SysMineralPowder> cementList = sysMineralPowderService.list(cementWrapper);


        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysMineralPowder::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 查询石粉表所在地区
     *
     * @return
     */

    @GetMapping("queryOtherAdmixturesRegions")
    public AjaxResult queryOtherAdmixturesRegions() {
        // 1. 查询所有水泥记录中的地区 id（去重）
        LambdaQueryWrapper<SysOtherAdmixtures> cementWrapper = new LambdaQueryWrapper<>();
        cementWrapper.select(SysOtherAdmixtures::getRegionName);
        List<SysOtherAdmixtures> cementList = sysOtherAdmixturesService.list(cementWrapper);


        if (cementList == null || cementList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 收集去重的地区 id
        Set<Integer> regionIds = cementList.stream()
                .map(SysOtherAdmixtures::getRegionName)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (regionIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 2. 查询地区表中对应的地区信息
        LambdaQueryWrapper<Region> regionWrapper = new LambdaQueryWrapper<>();
        regionWrapper.select(Region::getId, Region::getName, Region::getFullName, Region::getLevel, Region::getParentId)
                .in(Region::getId, regionIds);
        regionWrapper.in(Region::getId, regionIds);

        // 可按需要加排序或分页
        List<Region> regionList = regionService.list(regionWrapper);

        if (regionList == null || regionList.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 转成前端需要的 VO 对象
        List<RegionVO> voList = regionList.stream().map(region -> {
            RegionVO vo = new RegionVO();
            BeanUtils.copyProperties(region, vo);
            vo.setValue(region.getId());
            vo.setRegionName(region.getFullName());
            return vo;
        }).collect(Collectors.toList());

        // 4. 返回结果
        return AjaxResult.success(voList);
    }

    /**
     * 减水剂商家
     * @return
     */
    @GetMapping("queryWaterReducerSourceName")
    public AjaxResult queryWaterReducerSourceName() {
        // 构建查询条件
        LambdaQueryWrapper<SysWaterReducer> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SysWaterReducer::getSourceName)
                .eq(SysWaterReducer::getDeleteTime, 0)
                .isNotNull(SysWaterReducer::getSourceName)
                .groupBy(SysWaterReducer::getSourceName);

        // 执行查询
        List<SysWaterReducer> list = sysWaterReducerMapper.selectList(queryWrapper);

        // 提取 source_name 并去重（理论上 groupBy 已去重，这里是安全处理）
        List<String> sourceNames = list.stream()
                .map(SysWaterReducer::getSourceName)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        return AjaxResult.success(sourceNames);
    }

    @Autowired
    private SysEfficiencyAgentMapper sysEfficiencyAgentMapper;


    /**
     * 外加剂商家
     * @return
     */
    @GetMapping("queryEfficiencyAgentSourceName")
    public AjaxResult queryEfficiencyAgentSourceName() {
        // 构建查询条件
        LambdaQueryWrapper<SysEfficiencyAgent> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SysEfficiencyAgent::getSourceName)
                .eq(SysEfficiencyAgent::getDeleteTime, 0)
                .isNotNull(SysEfficiencyAgent::getSourceName)
                .groupBy(SysEfficiencyAgent::getSourceName);

        // 执行查询
        List<SysEfficiencyAgent> list = sysEfficiencyAgentMapper.selectList(queryWrapper);

        // 提取 source_name 并去重（理论上 groupBy 已去重，这里是安全处理）
        List<String> sourceNames = list.stream()
                .map(SysEfficiencyAgent::getSourceName)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        return AjaxResult.success(sourceNames);
    }


    @Autowired
    private SysSwellingagentMapper sysSwellingagentMapper;

    /**
     * 膨胀剂商家
     * @return
     */
    @GetMapping("querySwellingagentSourceName")
    public AjaxResult querySwellingagentSourceName() {
        // 构建查询条件
        LambdaQueryWrapper<SysSwellingagent> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SysSwellingagent::getSourceName)
                .eq(SysSwellingagent::getDeleteTime, 0)
                .isNotNull(SysSwellingagent::getSourceName)
                .groupBy(SysSwellingagent::getSourceName);

        // 执行查询
        List<SysSwellingagent> list = sysSwellingagentMapper.selectList(queryWrapper);

        // 提取 source_name 并去重（理论上 groupBy 已去重，这里是安全处理）
        List<String> sourceNames = list.stream()
                .map(SysSwellingagent::getSourceName)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        return AjaxResult.success(sourceNames);
    }

}
